package com.moxing.admin.common.utils;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * RedisUtil
 */
@Slf4j
@Component
public class RedisUtil {

    private static RedisTemplate<String, Object> redisTemplate;

    private static final Long RELEASE_SUCCESS = 1L;

    private static final long timeout = 10000; //获取锁的超时时间  毫秒


    /**
     * 超过1秒添加缓慢标识
     */
    private static final int slow_time = 1000;
    private static final String slow_flag = "redis_slow";


    public static RedisTemplate<String, Object> getRedisTemplate() {
        return redisTemplate;
    }

    private static JedisConnectionFactory factory;

    public static JedisConnectionFactory getFactory() {
        return factory;
    }

    @Autowired
    public void setRedisTemplate(@Qualifier("mainRedisTemplate")RedisTemplate<String, Object> mainRedisTemplate) {
        log.info("初始化redisutil:" + (mainRedisTemplate != null));
        RedisUtil.redisTemplate = mainRedisTemplate;
    }

    /**
     * mainRedisTemplate放在这里是为了保证RedisClusterConfig里面的@Bean("mainRedisTemplate")在此方法之前创建，
     * 否则执行完此方法会自动执行上面的setRedisTemplate，然后mainRedisTemplate还没创建导致异常
     * @param redisConnectionFactory1
     * @param mainRedisTemplate
     */
    @Autowired
    public void setFactory(@Qualifier("redisConnectionFactory")JedisConnectionFactory redisConnectionFactory1,@Qualifier("mainRedisTemplate")RedisTemplate<String, Object> mainRedisTemplate) {
        RedisUtil.factory = redisConnectionFactory1;
    }

    public static boolean checkRedis() {
        String ping = factory.getClusterConnection().ping();
        return "PONG".equals(ping);
    }

    // =============================common============================

    /**
     * 指定缓存失效时间
     *
     * @param key  键
     * @param time 时间(秒)
     * @return
     */
    public static boolean expire(String key, long time) {
        long start = System.currentTimeMillis();
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            log.error("------指定缓存失效时间失败-------：" + e.getMessage());
            return false;
        } finally {
            long costTime = System.currentTimeMillis() - start;
            log.info("指定缓存失效时间结束,参数[{}-{}],耗时{}", key, time, costTime > slow_time ? costTime + slow_flag : costTime);
        }
    }

    /**
     * 刷新缓存失效时间
     *
     * @param key 键
     * @return
     */
    public static boolean flushExpire(String key) {
        long start = System.currentTimeMillis();
        try {
            redisTemplate.expire(key, getExpire(key), TimeUnit.SECONDS);
            return true;
        } catch (Exception e) {
            log.error("------刷新缓存失效时间失败-------：" + e.getMessage());
            return false;
        } finally {
            long costTime = System.currentTimeMillis() - start;
            log.info("刷新缓存失效时间结束,参数[{}],耗时{}", key, costTime > slow_time ? costTime + slow_flag : costTime);
        }
    }

    /**
     * 根据key 获取过期时间
     *
     * @param key 键 不能为null
     * @return 时间(秒) 返回0代表为永久有效
     */
    public static long getExpire(String key) {

        long start = System.currentTimeMillis();
        try {
            return redisTemplate.getExpire(key, TimeUnit.SECONDS);
        } finally {
            long costTime = System.currentTimeMillis() - start;
            log.info("获取过期时间结束,参数[{}],耗时{}", key, costTime > slow_time ? costTime + slow_flag : costTime);
        }
    }

    /**
     * 判断key是否存在
     *
     * @param key 键
     * @return true 存在 false不存在
     */
    public static boolean hasKey(String key) {
        long start = System.currentTimeMillis();
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            log.error("------判断key是否存在失败-------：" + e.getMessage());
            return false;
        } finally {
            long costTime = System.currentTimeMillis() - start;
            log.info("判断key是否存在结束,参数[{}],耗时{}", key, costTime > slow_time ? costTime + slow_flag : costTime);
        }
    }


    /**
     * 删除缓存
     *
     * @param key 可以传一个值 或多个
     */
    public static void del(String... key) {
        long start = System.currentTimeMillis();
        try {
            if (key != null && key.length > 0) {
                if (key.length == 1) {
                    redisTemplate.delete(key[0]);
                } else {
                    redisTemplate.delete(String.valueOf(CollectionUtils.arrayToList(key)));
                }
            }
        } finally {
            long costTime = System.currentTimeMillis() - start;
            log.info("删除缓存结束,参数[{}],耗时{}", key, costTime > slow_time ? costTime + slow_flag : costTime);
        }

    }

    // ============================String=============================

    /**
     * 普通缓存获取
     *
     * @param key 键
     * @return 值
     */
    public static Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    /**
     * 普通缓存获取
     *
     * @param key 键
     * @return 值
     */
    public static String getValue(String key) {
        return key == null ? null : (String) redisTemplate.opsForValue().get(key);
    }

    /**
     * HashGet
     *
     * @param key   键 不能为null
     * @param clazz 获取类型
     * @param <T>
     * @return
     */
    public static <T> T get(String key, Class<T> clazz) {
        Object mapItem = get(key);
        return convertTo(mapItem, clazz);
    }

    /**
     * HashGet
     * 获取value并刷新持续时间
     *
     * @param key   键 不能为null
     * @param clazz 获取类型
     * @param <T>
     * @return
     */
    public static <T> T getAndFlushExpire(String key, Class<T> clazz) {
//        long start = System.currentTimeMillis();
//        try {
        Object mapItem = get(key);
        if (mapItem != null) {
            flushExpire(key);
        }
        return convertTo(mapItem, clazz);
    }

    /**
     * 普通缓存放入
     *
     * @param key   键
     * @param value 值
     * @return true成功 false失败
     */
    public static boolean set(String key, Object value) {
//        long start = System.currentTimeMillis();
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            log.error("------普通缓存放入失败-------", e);
            return false;
        }
//        finally {
//            long costTime = System.currentTimeMillis() - start;
//            log.info("普通缓存放入,参数[{}],耗时{}", key, costTime > slow_time ? costTime + slow_flag : costTime);
//        }
    }

    /**
     * 普通缓存放入并设置时间
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒) time要大于0 如果time小于等于0 将设置无限期
     * @return true成功 false 失败
     */
    public static boolean setValueAndSeconds(String key, Object value, long time) {
//        long start = System.currentTimeMillis();
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            log.error("------普通缓存放入并设置时间失败-------", e);
            return false;
        }
    }


    //---------------------------------对象以json字符串形式保存，不使用redis的序列化----------------------------
    /**
     * 普通对象缓存放入
     *
     * @param key   键
     * @param value 值
     * @return true成功 false失败
     */
    public static boolean setWithJsonString(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, JSON.toJSONString(value));
            return true;
        } catch (Exception e) {
            log.error("------普通缓存放入失败-------", e);
            return false;
        }
    }

    /**
     * 普通缓存放入并设置时间
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒) time要大于0 如果time小于等于0 将设置无限期
     * @return true成功 false 失败
     */
    public static boolean setValueAndSecondsWithJsonString(String key, Object value, long time) {
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set(key, JSON.toJSONString(value), time, TimeUnit.SECONDS);
            } else {
                setWithJsonString(key, value);
            }
            return true;
        } catch (Exception e) {
            log.error("------普通缓存放入并设置时间失败-------", e);
            return false;
        }
    }

    /**
     * 获取redis中以json字符串保存的对象
     *
     * @param key
     * @param
     * @param
     * @return
     */
    public static <T> T getWithJsonString(String key, Class<T> clazz) {
        try {
            String o = (String) redisTemplate.opsForValue().get(key);
            return JSON.parseObject(o, clazz);
        } catch (Exception e) {
            log.error("获取缓存失败",e);
            return null;
        }
    }

    /**
     * 获取redis中以json字符串保存的列表
     *
     * @param key
     * @param
     * @param
     * @return
     */
    public static <T> List<T> getJsonArray(String key, Class<T> clazz) {
        try {
            String o = (String) redisTemplate.opsForValue().get(key);
            return JSON.parseArray(o, clazz);
        } catch (Exception e) {
            log.error("获取缓存失败",e);
            return null;
        }
    }

    /**
     * 递增
     *
     * @param key   键
     * @param delta 要增加几(大于0)
     * @return
     */
    public static long incr(String key, long delta) {
        long start = System.currentTimeMillis();
        if (delta < 0) {
            throw new RuntimeException("递增因子必须大于0");
        }
        try {
            return redisTemplate.opsForValue().increment(key, delta);
        } finally {
            long costTime = System.currentTimeMillis() - start;
            log.info("key递增结束,参数[{}],耗时{}", key, costTime > slow_time ? costTime + slow_flag : costTime);
        }
    }

    /**
     * 递增
     *
     * @param key   键
     * @param delta 要增加几(大于0)
     * @return
     */
    public static void incrAndExpire(String key, long delta, long seconds) {
        long start = System.currentTimeMillis();
        if (delta < 0) {
            throw new RuntimeException("递增因子必须大于0");
        }
        try {
            redisTemplate.opsForValue().increment(key, delta);
            redisTemplate.expire(key,seconds,TimeUnit.SECONDS);
        } finally {
            long costTime = System.currentTimeMillis() - start;
            log.info("key递增结束,参数[{}],耗时{}", key, costTime > slow_time ? costTime + slow_flag : costTime);
        }
    }

    /**
     * 递减
     *
     * @param key   键
     * @param delta 要减少几(小于0)
     * @return
     */
    public static long decr(String key, long delta) {
        long start = System.currentTimeMillis();
        if (delta < 0) {
            throw new RuntimeException("递减因子必须大于0");
        }
        try {
            return redisTemplate.opsForValue().increment(key, -delta);
        } finally {
            long costTime = System.currentTimeMillis() - start;
            log.info("key递减结束,参数[{}],耗时{}", key, costTime > slow_time ? costTime + slow_flag : costTime);
        }
    }


    // ================================Map=================================

    /**
     * HashGet
     *
     * @param key  键 不能为null
     * @param item 项 不能为null
     * @return 值
     */
    public static Object getMapItem(String key, String item) {
        long start = System.currentTimeMillis();
        try {
            return redisTemplate.opsForHash().get(key, item);
        } catch (Exception e) {

            log.error("------HashGet失败-------：" + e.getMessage());
            return null;
        } finally {
            long costTime = System.currentTimeMillis() - start;
            log.info("getMapItem,参数[{}-{}],耗时{}", key, item, costTime > slow_time ? costTime + slow_flag : costTime);
        }
    }

    /**
     * HashGet
     *
     * @param key   键 不能为null
     * @param item  项 不能为null
     * @param clazz 获取类型
     * @param <T>
     * @return
     */
    public static <T> T getMapItem(String key, String item, Class<T> clazz) {
        long start = System.currentTimeMillis();
        try {
            Object mapItem = getMapItem(key, item);
            return convertTo(mapItem, clazz);
        } finally {
            long costTime = System.currentTimeMillis() - start;
            log.info("getMapItem,参数[{}-{}],耗时{}", key, item, costTime > slow_time ? costTime + slow_flag : costTime);
        }
    }

    /**
     * 获取hashKey对应的所有键值
     *
     * @param key 键
     * @return 对应的多个键值
     */
    public static Map<Object, Object> getMap(String key) {
        long start = System.currentTimeMillis();
        try {
            return redisTemplate.opsForHash().entries(key);
        } finally {
            long costTime = System.currentTimeMillis() - start;
            log.info("getMap,参数[{}],耗时{}", key, costTime > slow_time ? costTime + slow_flag : costTime);
        }
    }

    /**
     * setMap
     *
     * @param key 键
     * @param map 对应多个键值
     * @return true 成功 false 失败
     */
    public static boolean setMap(String key, Map<String, ?> map) {
        long start = System.currentTimeMillis();
        try {
            redisTemplate.opsForHash().putAll(key, map);
            return true;
        } catch (Exception e) {
            log.error("------setMap失败-------：" + e.getMessage());
            return false;
        } finally {
            long costTime = System.currentTimeMillis() - start;
            log.info("setMap,参数[{}],耗时{}", key, costTime > slow_time ? costTime + slow_flag : costTime);
        }
    }

    /**
     * HashSet 并设置时间  map<‘membre’,sessionMap<sessionId , MemberVO>> map<‘shop’,sessionMap<sessionId , ShopUserVO>>
     *
     * @param key  键
     * @param map  对应多个键值
     * @param time 时间(秒)
     * @return true成功 false失败
     */
    public static boolean setMap(String key, Map<String, ?> map, long time) {
        long start = System.currentTimeMillis();
        try {
            redisTemplate.opsForHash().putAll(key, map);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {

            log.error("------HashSet失败-------：" + e.getMessage());
            return false;
        } finally {
            long costTime = System.currentTimeMillis() - start;
            log.info("setMap,参数[{}],耗时{}", key, costTime > slow_time ? costTime + slow_flag : costTime);
        }
    }

    /**
     * 普通缓存放入
     *
     * @param key   键
     * @param value 值
     * @param time  超时时间
     * @return true成功 false失败
     */
    public static boolean setIfAbsent(String key, Object value, int time) {
        long start = System.currentTimeMillis();
        try {
            return redisTemplate.opsForValue().setIfAbsent(key, value, time, TimeUnit.SECONDS);
        } catch (Exception e) {
            log.error("------普通缓存放入失败-------", e);
            return false;
        } finally {
            long costTime = System.currentTimeMillis() - start;
            log.info("setIfAbsent,参数[{}],耗时{}", key, costTime > slow_time ? costTime + slow_flag : costTime);
        }
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @return true 成功 false失败
     */
    public static boolean setMapItem(String key, String item, Object value) {
        long start = System.currentTimeMillis();
        try {
            redisTemplate.opsForHash().put(key, item, value);
            return true;
        } catch (Exception e) {

            log.error("------hash表中放入数据失败-------：" + e.getMessage());
            return false;
        } finally {
            long costTime = System.currentTimeMillis() - start;
            log.info("setMapItem,参数[{}],耗时{}", key, costTime > slow_time ? costTime + slow_flag : costTime);
        }
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @param time  时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
     * @return true 成功 false失败
     */
    public static boolean setMapItem(String key, String item, Object value, long time) {
        long start = System.currentTimeMillis();
        try {
            redisTemplate.opsForHash().put(key, item, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {

            log.error("------hash表中放入数据并设置时间失败-------：" + e.getMessage());
            return false;
        } finally {
            long costTime = System.currentTimeMillis() - start;
            log.info("setMapItem,参数[{}-{}],耗时{}", key,item, costTime > slow_time ? costTime + slow_flag : costTime);
        }
    }

    /**
     * 删除hash表中的值
     *
     * @param key  键 不能为null
     * @param item 项 可以使多个 不能为null
     */
    public static boolean delMapItem(String key, Object... item) {
        long start = System.currentTimeMillis();
        try {
            redisTemplate.opsForHash().delete(key, item);
            return true;
        } catch (Exception e) {

            log.error("------删除hash表中的值失败-------：" + e.getMessage());
            return false;
        }finally {
            long costTime = System.currentTimeMillis() - start;
            log.info("delMapItem,参数[{}],耗时{}", key, costTime > slow_time ? costTime + slow_flag : costTime);
        }
    }

    /**
     * 加锁，无阻塞
     *
     * @param
     * @param
     * @return
     */
    public static Boolean tryLock(String key, String value, long expireTime) {

        Long start = System.currentTimeMillis();
        try {
            for (; ; ) {
                //SET命令返回OK ，则证明获取锁成功
                Boolean ret = redisTemplate.opsForValue().setIfAbsent(key, value, expireTime, TimeUnit.SECONDS);
                if (ret) {
                    return true;
                }
                //否则循环等待，在timeout时间内仍未获取到锁，则获取失败
                long end = System.currentTimeMillis() - start;
                if (end >= timeout) {
                    return false;
                }
            }
        } finally {
            long costTime = System.currentTimeMillis() - start;
            log.info("tryLock,参数[{}-{}],耗时{}", key,value, costTime > slow_time ? costTime + slow_flag : costTime);
        }

    }

    /**
     * 解锁
     *
     * @param
     * @param
     * @return
     */
    public static Boolean unlock(String key, String value) {
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";

        RedisScript<String> redisScript = new DefaultRedisScript<>(script, String.class);

        Object result = redisTemplate.execute(redisScript, Collections.singletonList(key), value);
        if (RELEASE_SUCCESS.equals(result)) {
            return true;
        }

        return false;
    }


    /**
     * 判断hash表中是否有该项的值
     *
     * @param key  键 不能为null
     * @param item 项 不能为null
     * @return true 存在 false不存在
     */
    public static boolean hasMapItem(String key, String item) {
        long start = System.currentTimeMillis();
        try {
            return redisTemplate.opsForHash().hasKey(key, item);
        } finally {
            long costTime = System.currentTimeMillis() - start;
            log.info("hasMapItem,参数[{}-{}],耗时{}", key,item, costTime > slow_time ? costTime + slow_flag : costTime);
        }
    }

    /**
     * hash递增 如果不存在,就会创建一个 并把新增后的值返回
     *
     * @param key  键
     * @param item 项
     * @param by   要增加几(大于0)
     * @return
     */
    public static double inrMapItem(String key, String item, double by) {
        long start = System.currentTimeMillis();
        try {
            return redisTemplate.opsForHash().increment(key, item, by);
        } finally {
            long costTime = System.currentTimeMillis() - start;
            log.info("inrMapItem,参数[{}-{}],耗时{}", key,item, costTime > slow_time ? costTime + slow_flag : costTime);
        }
    }

    /**
     * hash递减
     *
     * @param key  键
     * @param item 项
     * @param by   要减少记(小于0)
     * @return
     */
    public static double deductMapItem(String key, String item, double by) {
        long start = System.currentTimeMillis();
        try {
            return redisTemplate.opsForHash().increment(key, item, -by);
        } finally {
            long costTime = System.currentTimeMillis() - start;
            log.info("deductMapItem,参数[{}-{}],耗时{}", key,item, costTime > slow_time ? costTime + slow_flag : costTime);
        }
    }


    // ============================set=============================

    /**
     * 根据key获取Set中的所有值
     *
     * @param key 键
     * @return
     */
    public static Set<Object> sGet(String key) {
        long start = System.currentTimeMillis();
        try {
            return redisTemplate.opsForSet().members(key);
        } catch (Exception e) {

            log.error("------根据key获取Set中的所有值失败-------：" + e.getMessage());
            return null;
        }finally {
            long costTime = System.currentTimeMillis() - start;
            log.info("sGet,参数[{}],耗时{}", key, costTime > slow_time ? costTime + slow_flag : costTime);
        }
    }

    /**
     * 根据value从一个set中查询,是否存在
     *
     * @param key   键
     * @param value 值
     * @return true 存在 false不存在
     */
    public static boolean sHasKey(String key, Object value) {
        long start = System.currentTimeMillis();
        try {
            return redisTemplate.opsForSet().isMember(key, value);
        } catch (Exception e) {

            log.error("------根据value从一个set中查询,是否存在失败-------：" + e.getMessage());
            return false;
        }finally {
            long costTime = System.currentTimeMillis() - start;
            log.info("sHasKey,参数[{}],耗时{}", key, costTime > slow_time ? costTime + slow_flag : costTime);
        }
    }

    /**
     * 将数据放入set缓存
     *
     * @param key    键
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public static long sSet(String key, Object... values) {
        long start = System.currentTimeMillis();
        try {
            return redisTemplate.opsForSet().add(key, values);
        } catch (Exception e) {

            log.error("------将数据放入set缓存失败-------：" + e.getMessage());
            return 0;
        }finally {
            long costTime = System.currentTimeMillis() - start;
            log.info("sSet,参数[{}],耗时{}", key, costTime > slow_time ? costTime + slow_flag : costTime);
        }
    }

    /**
     * 将set数据放入缓存
     *
     * @param key    键
     * @param time   时间(秒)
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public static long sSetAndTime(String key, long time, Object... values) {
        long start = System.currentTimeMillis();
        try {
            Long count = redisTemplate.opsForSet().add(key, values);
            if (time > 0) {
                expire(key, time);
            }
            return count;
        } catch (Exception e) {

            log.error("------将set数据放入缓存失败-------：" + e.getMessage());
            return 0;
        }finally {
            long costTime = System.currentTimeMillis() - start;
            log.info("sSetAndTime,参数[{}-{}],耗时{}", key,time, costTime > slow_time ? costTime + slow_flag : costTime);
        }
    }

    /**
     * 获取set缓存的长度
     *
     * @param key 键
     * @return
     */
    public static long sGetSetSize(String key) {
        long start = System.currentTimeMillis();
        try {
            return redisTemplate.opsForSet().size(key);
        } catch (Exception e) {

            return 0;
        }finally {
            long costTime = System.currentTimeMillis() - start;
            log.info("sGetSetSize,参数[{}],耗时{}", key, costTime > slow_time ? costTime + slow_flag : costTime);
        }
    }

    /**
     * 移除值为value的
     *
     * @param key    键
     * @param values 值 可以是多个
     * @return 移除的个数
     */
    public static long setRemove(String key, Object... values) {
        long start = System.currentTimeMillis();
        try {
            Long count = redisTemplate.opsForSet().remove(key, values);
            return count;
        } catch (Exception e) {

            return 0;
        }finally {
            long costTime = System.currentTimeMillis() - start;
            log.info("setRemove,参数[{}],耗时{}", key, costTime > slow_time ? costTime + slow_flag : costTime);
        }
    }

    // ===============================list=================================

    /**
     * 获取list缓存的内容
     *
     * @param key        键
     * @param startIndex 开始
     * @param end        结束 0 到 -1代表所有值
     * @return
     */
    public static List<Object> lGet(String key, long startIndex, long end) {
        long start = System.currentTimeMillis();
        try {
            return redisTemplate.opsForList().range(key, startIndex, end);
        } catch (Exception e) {

            return null;
        }finally {
            long costTime = System.currentTimeMillis() - start;
            log.info("lGet,参数[{}-{}-{}],耗时{}", key,startIndex,end, costTime > slow_time ? costTime + slow_flag : costTime);
        }
    }

    /**
     * 获取list缓存的长度
     *
     * @param key 键
     * @return
     */
    public static long lGetListSize(String key) {
        long start = System.currentTimeMillis();
        try {
            return redisTemplate.opsForList().size(key);
        } catch (Exception e) {

            return 0;
        }finally {
            long costTime = System.currentTimeMillis() - start;
            log.info("lGetListSize,参数[{}],耗时{}", key, costTime > slow_time ? costTime + slow_flag : costTime);
        }
    }

    /**
     * 通过索引 获取list中的值
     *
     * @param key   键
     * @param index 索引 index>=0时， 0 表头，1 第二个元素，依次类推；index<0时，-1，表尾，-2倒数第二个元素，依次类推
     * @return
     */
    public static Object lGetIndex(String key, long index) {
        long start = System.currentTimeMillis();
        try {
            return redisTemplate.opsForList().index(key, index);
        } catch (Exception e) {

            return null;
        }finally {
            long costTime = System.currentTimeMillis() - start;
            log.info("lGetIndex,参数[{}-{}],耗时{}", key,index, costTime > slow_time ? costTime + slow_flag : costTime);
        }
    }

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @return
     */
    public static boolean lSet(String key, Object value) {
        long start = System.currentTimeMillis();
        try {
            redisTemplate.opsForList().rightPush(key, value);
            return true;
        } catch (Exception e) {

            return false;
        }finally {
            long costTime = System.currentTimeMillis() - start;
            log.info("lSet,参数[{}],耗时{}", key, costTime > slow_time ? costTime + slow_flag : costTime);
        }
    }

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒)
     * @return
     */
    public static boolean lSet(String key, Object value, long time) {
        long start = System.currentTimeMillis();
        try {
            redisTemplate.opsForList().rightPush(key, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {

            return false;
        }finally {
            long costTime = System.currentTimeMillis() - start;
            log.info("lSet,参数[{}],耗时{}", key, costTime > slow_time ? costTime + slow_flag : costTime);
        }
    }

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @return
     */
    public static boolean lSet(String key, List<Object> value) {
        long start = System.currentTimeMillis();
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            return true;
        } catch (Exception e) {

            return false;
        }finally {
            long costTime = System.currentTimeMillis() - start;
            log.info("lSet,参数[{}],耗时{}", key, costTime > slow_time ? costTime + slow_flag : costTime);
        }
    }

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒)
     * @return
     */
    public static boolean lSet(String key, List<Object> value, long time) {
        long start = System.currentTimeMillis();
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {

            return false;
        }finally {
            long costTime = System.currentTimeMillis() - start;
            log.info("lSet,参数[{}],耗时{}", key, costTime > slow_time ? costTime + slow_flag : costTime);
        }
    }

    /**
     * 根据索引修改list中的某条数据
     *
     * @param key   键
     * @param index 索引
     * @param value 值
     * @return
     */
    public static boolean lUpdateIndex(String key, long index, Object value) {
        long start = System.currentTimeMillis();
        try {
            redisTemplate.opsForList().set(key, index, value);
            return true;
        } catch (Exception e) {

            return false;
        }finally {
            long costTime = System.currentTimeMillis() - start;
            log.info("lUpdateIndex,参数[{}-{}],耗时{}", key,index, costTime > slow_time ? costTime + slow_flag : costTime);
        }
    }

    /**
     * 移除N个值为value
     *
     * @param key   键
     * @param count 移除多少个
     * @param value 值
     * @return 移除的个数
     */
    public static long lRemove(String key, long count, Object value) {
        long start = System.currentTimeMillis();
        try {
            Long remove = redisTemplate.opsForList().remove(key, count, value);
            return remove;
        } catch (Exception e) {

            return 0;
        }finally {
            long costTime = System.currentTimeMillis() - start;
            log.info("lRemove,参数[{}-{}],耗时{}", key,count, costTime > slow_time ? costTime + slow_flag : costTime);
        }
    }

    /**
     * 获取
     *
     * @param obj
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T convertTo(Object obj, Class<T> clazz) {
        if (clazz.isInstance(obj)) {
            return clazz.cast(obj);
        }
        return null;
    }

}
